package edu.spec.wechat.controller;

import edu.spec.student.model.Student;
import edu.spec.student.service.iface.IStudentService;
import edu.spec.basic.model.User;
import edu.spec.basic.model.dto.MvcReturn;
import edu.spec.basic.service.iface.IUserService;
import org.madgecko.basic.kit.BasicKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by MadFrog on 2016/11/6.
 */
@Controller
public class BindingController {

    @Autowired
    private IStudentService studentService;
    @Autowired
    private IUserService userService;

    @ResponseBody
    @RequestMapping(value = "student/bind", method = RequestMethod.POST)
    public Object bindStudent(@RequestParam String xh, @RequestParam String sfzh, HttpSession session){
        String message = "";
        String openId = (String) session.getAttribute("openId");
        Student stu = studentService.loadByXhAndSfzh(xh, sfzh);
        if(stu==null){
            message = "校验失败，请核对学号和身份证号！";
        } else {
            // 判断是否已经绑定
            String dbOpenId = stu.getOpenId();
            if (!BasicKit.isEmpty(dbOpenId)){
                message = "您已经绑定信息，请不要重复绑定！";
            }else{
                stu.setOpenId(openId);
                studentService.update(stu);
                session.setAttribute("user", stu);
                message = "绑定成功!";
            }
        }
        return new MvcReturn(true, message);
    }

    @ResponseBody
    @RequestMapping(value = "teacher/bind", method = RequestMethod.POST)
    public Object bindTeacher(@RequestParam String jgh, @RequestParam String sfzh, HttpSession session){
        String message = "";
        String openId = (String) session.getAttribute("openId");
        User teacher = userService.loadByName(jgh);
        if(teacher==null){
            message = "绑定失败，请检查教工号！";
        } else if(!teacher.getIdNumber().equals(sfzh)){
            message = "绑定失败，请检查身份证号！";
        } else {
            // 判断是否已经绑定
            String dbOpenId = teacher.getOpenId();
            if (!BasicKit.isEmpty(dbOpenId)){
                message = "您已经绑定信息，请不要重复绑定！";
            }else{
                teacher.setOpenId(openId);
                userService.update(teacher);
                session.setAttribute("user", teacher);
                message = "绑定成功!";
            }
        }
        return new MvcReturn(true, message);
    }

}
